package com.nickstumpos.android.easyVolume.events.recievers;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import org.apache.commons.codec.binary.Base64;

import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import com.nickstumpos.android.easyVolume.constants.EVCONSTANTS;
import com.nickstumpos.android.easyVolume.events.Dto.EventTriggerDto;
import com.nickstumpos.android.easyVolume.preset.service.PresetService;

public class ApplyPresetBlueToothHsReciever extends BroadcastReceiver {

	private PresetService			presetService;
	private SharedPreferences	settings;

	@Override
	public void onReceive(Context context, Intent i) {
		this.presetService = new PresetService(context);
		this.settings = context.getSharedPreferences(EVCONSTANTS.PREFS_NAME, 0);
		if (BluetoothClass.Device.Major.AUDIO_VIDEO == ((BluetoothDevice) i
				.getParcelableExtra(android.bluetooth.BluetoothDevice.EXTRA_DEVICE))
				.getBluetoothClass().getMajorDeviceClass()) {
			String old = this.settings.getString(EVCONSTANTS.EVENT_SCHED_DTO, null);
			if (old != null) {
				final byte[] buf = Base64.decodeBase64(old.getBytes());
				ObjectInputStream in = null;
				try {
					in = new ObjectInputStream(new ByteArrayInputStream(buf));
					EventTriggerDto inflated = (EventTriggerDto) in.readObject();
					if (inflated != null) {
						if (android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED.equals(i
								.getAction())) {
							if (inflated.isBtConnectActive()) {
								if (inflated.getBtConnectPreset() != null) {
									this.presetService.applyPreset(inflated.getBtConnectPreset());
								}
							}
						} else if (android.bluetooth.BluetoothDevice.ACTION_ACL_DISCONNECTED
								.equals(i.getAction())) {
							if (inflated.isBtDisconnectActive()) {
								if (inflated.getBtDisconnectPreset() != null) {
									this.presetService.applyPreset(inflated
											.getBtDisconnectPreset());
								}
							}
						}
					}
				} catch (final IOException e) {
				} catch (final ClassNotFoundException e) {
				}
			}
		}
	}
}